package a2022.a20221008;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @author lenovo
 * @date 2022/10/8
 */
public class a {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(
                advantageCount2(
                        new int[]{2, 7, 11, 15},
                        new int[]{1, 10, 4, 11}
                )));
    }

    public static int[] advantageCount(int[] nums1, int[] nums2) {
        int length = nums1.length;
        Arrays.sort(nums1);
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            list.add(new int[]{nums2[i], i});
        }
        Collections.sort(list, (l1, l2) -> l1[0] - l2[0]);
        int right = length - 1;
        int left = 0;
        for (int i = length - 1; i > -1; i--) {
            if (list.get(i)[0] < nums1[right]) {
                list.get(i)[0] = nums1[right];
                right--;
            }else {
                list.get(i)[0] = nums1[left];
                left++;
            }
        }
        Collections.sort(list, (l1, l2) -> l1[1] - l2[1]);
        int[] nums = new int[length];
        for (int i = 0; i < length; i++) {
            nums[i] = list.get(i)[0];
        }
        return nums;
    }

    public static int[] advantageCount2(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int[] ans = new int[n];
        Arrays.sort(nums1);
        Integer[] ids = IntStream.range(0, n).boxed().toArray(Integer[]::new);
        Arrays.sort(ids, (i, j) -> nums2[i] - nums2[j]);
        int left = 0, right = n - 1;
        for (int x : nums1)
            ans[x > nums2[ids[left]] ? ids[left++] : ids[right--]] = x;
        return ans;
    }

}
